import { useState, useEffect } from "react";
import {
  Form,
  Input,
  Button,
  Modal,
  Card,
  message,
  Switch,
  Space,
  Tooltip,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  CopyrightOutlined,
  SunOutlined,
  MoonOutlined,
} from "@ant-design/icons";
import { useNavigate, Link } from "react-router-dom";
import { login, getUserProfile } from "../api/users";
import { setUserRole } from "../utils/auth";
import { useTheme } from "../contexts/ThemeContext";

import { Typography } from "antd";

const { Title, Paragraph } = Typography;

export default function Login() {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { isDarkMode, toggleDarkMode } = useTheme();

  // 检查是否有注册成功后传递的用户信息
  useEffect(() => {
    const registeredUserInfo = localStorage.getItem("registeredUserInfo");
    if (registeredUserInfo) {
      try {
        const userInfo = JSON.parse(registeredUserInfo);
        form.setFieldsValue({
          name: userInfo.name,
          password: userInfo.password,
        });
        localStorage.removeItem("registeredUserInfo"); // 使用后清除
        message.info("注册成功！已为您填入登录信息");
      } catch (error) {
        console.error("解析注册用户信息失败:", error);
      }
    }
  }, [form]);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const res = await login(values);
      if (res.code !== 1) {
        throw new Error(res.message);
      }
      // 新接口结构：res.data = { userId, token, username }
      localStorage.setItem("token", res.data.token);
      localStorage.setItem("userId", res.data.userId);
      localStorage.setItem("username", res.data.username);

      // 获取用户完整信息，包括角色
      try {
        const userProfileRes = await getUserProfile(res.data.userId);
        if (userProfileRes.code === 1 && userProfileRes.data) {
          const userRole = userProfileRes.data.role || "user";
          setUserRole(userRole);
          localStorage.setItem("userRole", userRole);
        }
      } catch (error) {
        console.warn("获取用户角色失败，默认为普通用户", error);
        setUserRole("user");
        localStorage.setItem("userRole", "user");
      }

      // 设置一个标记，表示刚刚登录成功
      localStorage.setItem("justLoggedIn", "true");

      // 跳转到首页
      window.location.href = "/";
    } catch (e) {
      message.error("登录失败");
    }
    setLoading(false);
  };

  return (
    <div
      style={{
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        background: isDarkMode
          ? "linear-gradient(135deg, #1f1f1f 0%, #2a2a2a 100%)"
          : "linear-gradient(135deg, #f0f5ff 0%, #e6f7ff 100%)",
        position: "relative",
        overflow: "hidden",
        transition: "background 0.3s ease",
      }}>
      {/* 主题切换按钮 */}
      <div
        style={{
          position: "absolute",
          top: 20,
          right: 20,
          zIndex: 10,
        }}>
        <Tooltip title={isDarkMode ? "切换到浅色模式" : "切换到深色模式"}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "8px",
              padding: "8px 12px",
              borderRadius: "6px",
              backgroundColor: isDarkMode ? "#2a2a2a" : "#f5f5f5",
              border: `1px solid ${isDarkMode ? "#434343" : "#d9d9d9"}`,
              cursor: "pointer",
              transition: "all 0.3s ease",
            }}
            onClick={toggleDarkMode}>
            <Space size="small">
              {isDarkMode ? (
                <MoonOutlined style={{ color: "#1890ff" }} />
              ) : (
                <SunOutlined style={{ color: "#faad14" }} />
              )}
              <span
                style={{
                  fontSize: "12px",
                  color: isDarkMode ? "#fff" : "#666",
                }}>
                {isDarkMode ? "深色" : "浅色"}
              </span>
            </Space>
            <Switch
              size="small"
              checked={isDarkMode}
              onChange={toggleDarkMode}
              checkedChildren={<MoonOutlined />}
              unCheckedChildren={<SunOutlined />}
            />
          </div>
        </Tooltip>
      </div>

      {/* 左侧渐变圆形装饰 */}
      <div
        style={{
          position: "absolute",
          left: -120,
          top: "30%",
          width: 220,
          height: 220,
          background: isDarkMode
            ? "radial-gradient(circle at 60% 40%, #3a3a3a 0%, #2a2a2a 80%)"
            : "radial-gradient(circle at 60% 40%, #91d5ff 0%, #e6f7ff 80%)",
          opacity: 0.35,
          borderRadius: "50%",
          zIndex: 0,
          filter: "blur(2px)",
          transition: "background 0.3s ease",
        }}
      />
      {/* 右侧渐变圆形装饰 */}
      <div
        style={{
          position: "absolute",
          right: -100,
          bottom: "18%",
          width: 180,
          height: 180,
          background: isDarkMode
            ? "radial-gradient(circle at 40% 60%, #404040 0%, #2a2a2a 80%)"
            : "radial-gradient(circle at 40% 60%, #bae7ff 0%, #e6f7ff 80%)",
          opacity: 0.32,
          borderRadius: "50%",
          zIndex: 0,
          filter: "blur(2px)",
          transition: "background 0.3s ease",
        }}
      />
      {/* 顶部小圆点装饰 */}
      <div
        style={{
          position: "absolute",
          top: 32,
          left: "50%",
          transform: "translateX(-50%)",
          width: 16,
          height: 16,
          background: isDarkMode ? "#1890ff44" : "#1890ff22",
          borderRadius: "50%",
          boxShadow: isDarkMode ? "0 0 8px #1890ff77" : "0 0 8px #1890ff55",
          zIndex: 1,
          transition: "all 0.3s ease",
        }}
      />
      <Card
        style={{
          width: 390,
          borderRadius: 18,
          boxShadow: isDarkMode
            ? "0 4px 32px rgba(0,0,0,0.3), 0 1.5px 8px rgba(0,0,0,0.2)"
            : "0 4px 32px #e6f7ff, 0 1.5px 8px #b3d8ff33",
          padding: 0,
          position: "relative",
          overflow: "hidden",
          transition: "box-shadow 0.3s cubic-bezier(.4,2,.6,1)",
          backgroundColor: isDarkMode ? "#2a2a2a" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        }}
        variant="outlined"
        styles={{
          body: { padding: "32px 32px 24px 32px" },
        }}
        hoverable>
        {/* 卡片底部渐变装饰 */}
        <div
          style={{
            position: "absolute",
            left: 0,
            bottom: 0,
            width: "100%",
            height: 60,
            background: isDarkMode
              ? "linear-gradient(90deg, #1f1f1f 0%, #3a3a3a 100%)"
              : "linear-gradient(90deg, #e6f7ff 0%, #bae7ff 100%)",
            opacity: 0.18,
            zIndex: 0,
            transition: "background 0.3s ease",
          }}
        />
        <div
          style={{
            textAlign: "center",
            marginBottom: 24,
            marginTop: 8,
            position: "relative",
            zIndex: 2,
          }}>
          <img
            src="/scnu-logo.png"
            alt="华师logo"
            style={{
              width: 56,
              marginBottom: 8,
              filter: "drop-shadow(0 2px 8px #bae7ff)",
            }}
          />
          <Title
            level={3}
            style={{
              color: "#1890ff",
              marginBottom: 0,
              letterSpacing: 2,
            }}>
            欢迎登录
          </Title>
          <Paragraph
            style={{
              color: isDarkMode ? "#bfbfbf" : "#888",
              marginBottom: 0,
              fontSize: 15,
              transition: "color 0.3s ease",
            }}>
            华师IT智能博客推荐与知识问答系统
          </Paragraph>
        </div>
        <Form
          form={form}
          onFinish={onFinish}
          layout="vertical"
          style={{ zIndex: 2, position: "relative" }}>
          <Form.Item
            name="name"
            rules={[{ required: true, message: "请输入用户名" }]}>
            <Input
              prefix={<UserOutlined style={{ color: "#1890ff" }} />}
              placeholder="用户名"
              size="large"
              autoComplete="username"
              style={{ borderRadius: 8 }}
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}>
            <Input.Password
              prefix={<LockOutlined style={{ color: "#1890ff" }} />}
              placeholder="密码"
              size="large"
              autoComplete="current-password"
              style={{ borderRadius: 8 }}
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
              style={{
                borderRadius: 8,
                background: "linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)",
                boxShadow: "0 2px 8px #bae7ff55",
                border: "none",
                fontWeight: 500,
                letterSpacing: 1,
              }}>
              登录
            </Button>
          </Form.Item>

          <Form.Item
            style={{ marginBottom: 0, textAlign: "center", marginTop: 16 }}>
            <span style={{ color: isDarkMode ? "#bfbfbf" : "#888" }}>
              还没有账号？
            </span>
            <Link
              to="/register"
              style={{
                color: "#1890ff",
                marginLeft: 8,
                textDecoration: "none",
              }}>
              立即注册
            </Link>
          </Form.Item>
        </Form>
      </Card>
      {/* 底部版权信息 */}
      <div
        style={{
          marginTop: 32,
          color: isDarkMode ? "#8c8c8c" : "#b3b3b3",
          fontSize: 13,
          letterSpacing: 1,
          display: "flex",
          alignItems: "center",
          gap: 4,
          userSelect: "none",
          transition: "color 0.3s ease",
        }}>
        <CopyrightOutlined /> 2025 华师IT智能博客推荐与知识问答系统
      </div>
    </div>
  );
}
